//
//  CTCConsultDetailTableViewController.m
//  CTC
//
//  Created by 李小龙 on 2017/3/17.
//  Copyright © 2017年 jieshuibao. All rights reserved.
//

#import "CTCConsultDetailTableViewController.h"
#import "CTCO2OConsultQuestionCell.h"
#import "CTCConsultAnsCell.h"
#import "CTCConsultAnswererCell.h"
#import "CTCAnswerResponderVC.h"
#import "CTCAnswerQuestionVC.h"

@interface CTCConsultDetailTableViewController ()<UIPopoverPresentationControllerDelegate>

/** 是否显示追问 */
@property (nonatomic, assign) BOOL showPersistBtn;


/** 回答的模型数据 */
@property (nonatomic, strong) CTCAnswerModel *answerModel;

@end

@implementation CTCConsultDetailTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"回答详情";
    
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"评价" style:UIBarButtonItemStyleDone target:self action:@selector(rightBarButtonItemDidClicked:)];
    
    self.tableView.backgroundColor = HEXCOLOR(0xEEEDEE);
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableFooterView = [UIView new];
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([CTCO2OConsultQuestionCell class]) bundle:nil] forCellReuseIdentifier:@"CTCO2OConsultQuestionCell"];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([CTCConsultAnsCell class]) bundle:nil] forCellReuseIdentifier:@"CTCConsultAnsCell"];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([CTCConsultAnswererCell class]) bundle:nil] forCellReuseIdentifier:@"CTCConsultAnswererCell"];
    
    self.tableView.estimatedRowHeight = 184;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
     self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadAnswer)];
    
    [self loadAnswer];
}


- (void)loadAnswer
{
    [MBProgressHUD showAnimationHUD];
    [RequestTool POST:kAnswerConsulDetailUrl
           parameters:@{@"uuid" : self.questionModel.uuid}
             progress:nil
              success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                  DeLog(@"responseObject  %@", responseObject);
                  [self stopRefresh];
                  NSInteger code = [responseObject[@"code"] intValue];
                  NSString *des = responseObject[@"des"];
                  if (code == 1) {
                      [MBProgressHUD hideHUD];
                      self.answerModel = [CTCAnswerModel yy_modelWithJSON:responseObject[@"data"]];
                      [self.tableView reloadData];
                  }
                  
                  else {
                      [MBProgressHUD showErrorMessage:des];
                      
                      if (code == 2) {
                          CTCLoginViewController *vc = [CTCLoginViewController viewControllerFromStoryboard];
                          MPWeakSelf(self);
                          vc.loginSuccess = ^(){
                              [weakself loadAnswer];
                          };
                          [self presentViewController:vc animated:YES completion:nil];
                      }
                  }
                  
              }
              failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                  DeLog(@"%@",error);
                  [self stopRefresh];
                  if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
                      [MBProgressHUD showErrorMessage:@"网络不给力，请检查网络"];
                  }
                  else {
                      [MBProgressHUD showErrorMessage:@"服务器繁忙"];
                  }
              }
     ];
}



- (void)stopRefresh
{
    !self.tableView.mj_header.isRefreshing ? : self.tableView.mj_header.endRefreshing;
    !self.tableView.mj_footer.isRefreshing ? : self.tableView.mj_footer.endRefreshing;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.answerModel.stage > 0 ? 2 : 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return section == 0 ? 1 : (self.answerModel.stage + 1);
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        CTCO2OConsultQuestionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CTCO2OConsultQuestionCell" forIndexPath:indexPath];
        cell.questionModel = self.questionModel;
        
        if ([self.questionModel.status isEqualToString:@"1"]) {
            cell.replyBtn.hidden = YES;
        } else if (self.answerModel
            && self.answerModel.content
            && self.answerModel.content.length) {
            cell.replyBtn.hidden = YES;
        }
        else {
            cell.replyBtn.hidden = NO;
        }
        
//        cell.showImage = CTCO2OConsultQuestionCellShowImageTypeShow;
        MPWeakSelf(self);
        
        cell.replyBtnClickBlock = ^(){
            UIStoryboard *story = [UIStoryboard storyboardWithName:@"CTCResponderVC" bundle:nil];
            CTCAnswerResponderVC *vc = [story instantiateViewControllerWithIdentifier:@"CTCAnswerResponderVC"];
            vc.uuid = self.questionModel.uuid;
            vc.fromType = CTCAnswerResponderFromTypeO2OList;
            vc.answerSuccessBlock = ^(){
                [weakself loadAnswer];
                NSLog(@"调没有  [weakself loadAnswer];");
                
//                MPStrongSelf(self);
//                if (self.answerSuccessBlock) {
//                    NSLog(@"调没有  weakself.answerSuccessBlock();");
//                    self.answerSuccessBlock();
//                }
            };
            
            [weakself.navigationController pushViewController:vc animated:YES];
        };
        return cell;
    }
    
    if (indexPath.row == 0) {
        CTCConsultAnswererCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CTCConsultAnswererCell" forIndexPath:indexPath];
        cell.answerModel = self.answerModel;
        return cell;
    }
    
    CTCConsultAnsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CTCConsultAnsCell"];
    
    cell.index = indexPath.row;
    cell.answerModel = self.answerModel;
    
    
    NSMutableArray *addQuestionArr = [NSMutableArray array];
    if (self.answerModel.firstAsked && self.answerModel.firstAsked.length) {
        [addQuestionArr addObject:self.answerModel.firstAsked];
    }
    
    if (self.answerModel.secondAsked && self.answerModel.secondAsked.length) {
        [addQuestionArr addObject:self.answerModel.secondAsked];
    }
    
    if (self.answerModel.thirdAasked && self.answerModel.thirdAasked.length) {
        [addQuestionArr addObject:self.answerModel.thirdAasked];
    }
//    cell.addQuestionCout = addQuestionArr.count;
    
    MPWeakSelf(self);
    cell.replyBtnClickBlock = ^(){
        UIStoryboard *story = [UIStoryboard storyboardWithName:@"CTCResponderVC" bundle:nil];
        CTCAnswerResponderVC *vc = [story instantiateViewControllerWithIdentifier:@"CTCAnswerResponderVC"];
        vc.uuid = self.questionModel.uuid;
        vc.fromType = CTCAnswerResponderFromTypeO2OList;
    
        
        vc.answerSuccessBlock = ^(){
            [weakself loadAnswer];
        };
        [weakself.navigationController pushViewController:vc animated:YES];
    };
    
    return cell;
}






- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0;
}


#pragma mark - 选

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}


#pragma mark - 

- (void)CTCConsultAnsCellAskBtnDidClicked:(CTCConsultAnsCell *)cell
{
//    CTCAddQuetionVC *vc = [[CTCAddQuetionVC alloc]init];
//    vc.uuid = self.aModel.uuid;
//    vc.url = kConsultO2OAskUrl;
//    MPWeakSelf(self);
//    [vc setAddQuetionBlock:^{
//        [weakself loadAnswer];
//    }];
//    
//    CTCNavigationController *nav = [[CTCNavigationController alloc] initWithRootViewController:vc];
//    [self presentViewController:nav animated:YES completion:nil];
}

@end
